package cn.jdy.plugins.wap;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.jdy.authority.entity.Organ;
import cn.jdy.authority.service.OrganService;
import cn.jdy.common.ctrl.BaseCtrl;
import cn.jdy.common.util.XMLUtil;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.util.DateUtil;
import cn.jdy.framework.util.StringUtil;
import cn.jdy.plugins.entity.ApplyCash;
import cn.jdy.plugins.entity.Line;
import cn.jdy.plugins.entity.Live;
import cn.jdy.plugins.entity.SecretKeyCet;
import cn.jdy.plugins.entity.SecretKeyl;
import cn.jdy.plugins.entity.WatchUser;
import cn.jdy.plugins.service.ApplyCashService;
import cn.jdy.plugins.service.LineService;
import cn.jdy.plugins.service.LiveService;
import cn.jdy.plugins.service.SecretKeyCetService;
import cn.jdy.plugins.service.SecretKeylService;
import cn.jdy.plugins.service.WatchUserService;
import cn.jdy.plugins.wap.util.ChatUtil;
import cn.jdy.plugins.wap.util.HttpUtils;
import cn.jdy.plugins.wap.util.RedPacketUtil;

/**
 * @title  用户提现操作类
 * @author ningqian
 * @since  2017-5-8
 */

@Controller
@RequestMapping("/applyCash")
public class ApplyCashCtrl extends BaseCtrl{
	@Autowired
	private ApplyCashService applyCashService;
	@Autowired
	private WatchUserService watchUserService;
	@Autowired
	private OrganService organService;
	@Autowired
	private LiveService liveService;
	@Autowired
	private LineService lineService;
	@Autowired
	private SecretKeylService secretKeylService;
	@Autowired
	private SecretKeyCetService secretKeyCetService;
	//微信参数配置  
	//企业付款接口地址
	private static final String TRANSFERS_PAY = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers"; 
	
//    private static String mch_id="1296239001";  
//    private static String appid = "wx003d8b600a48f618";   
//    private static String api_key="11111111111111111111111111111111";  
    

	/**
	 * 申请提现 进入提现界面
	 * @param 用户id
	 * @return
	 */
	@RequestMapping("/toApply")
	public ModelAndView toApply(@RequestParam("userOpenId") String userOpenId) {
		ModelAndView mv = new ModelAndView("/red/applyCash.jsp");
		//获取观看用户信息
		WatchUser user = watchUserService.findOne("userOpenId",userOpenId);
		mv.addObject("data", user);
		return mv;
	}
	
	

	/**
	 * 处理用户提现请求
	 * @param watchUser
	 * @return
	 */
	@RequestMapping("/apply")
	@ResponseBody
	public Map<String, Object> apply(@RequestParam("userOpenId") String userOpenId,
			@RequestParam("userNickName") String userNickName,@RequestParam("applyCash") double applyCash) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		String result = "申请成功!";
		try {
			//获取当前看用户信息
			WatchUser user = watchUserService.findOne("userOpenId",userOpenId);
			if(null != user){
				//当前余额 = 总额-申请提现金额
			    double currentMoney =  RedPacketUtil.sub(user.getTotal(), applyCash);
				user.setTotal(currentMoney);
				user.setUpdateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
				watchUserService.update(user);
				
				//新增一条提现记录
				ApplyCash cash = new ApplyCash();
				cash.setUserOpenId(userOpenId);
				cash.setUserNickName(userNickName);
				cash.setStatus("1");   //1-申请提现 ，2-成功， 3-失败
				cash.setApplyCash(applyCash);
				cash.setCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
				cash.setTotal(currentMoney);
				applyCashService.save(cash);
				
			}else{
				result = "申请失败，获取用户信息失败！";
			}
			
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "修改异常", e);
			result = "申请失败，连接失败！";
		}
		jsonMap.put("result", result);
		return jsonMap;
	} 
	
	
	
	/**
	 * 处理用户提现请求(接口)
	 * @param watchUser
	 * @return
	 */
	@RequestMapping("/applyBySys")
	@ResponseBody
	public Map<String, Object> applyBySys(@RequestParam("userOpenId") String userOpenId,@RequestParam("userNickName") String userNickName,@RequestParam("liveId") Long liveId,
			@RequestParam("applyCash") double applyCash,@RequestParam("appid") String appid,@RequestParam("mchid") String mchid,@RequestParam("apikey") String apikey) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		BaseLog.e(this.getClass(), "处理用户提现请求->userOpenId:"+userOpenId+",userNickName:"+userNickName+",liveId:"+liveId
				+",applyCash:"+applyCash+",appid:"+appid+",mchid="+mchid+",apikey:"+apikey);
		String result = "提现成功!";
		String statusCode = "2";  //1-成功 2-失败
		
		//新增一条提现记录
		ApplyCash cash = new ApplyCash();
		cash.setMch_id(mchid);
		cash.setUserOpenId(userOpenId);
		cash.setUserNickName(userNickName);
		cash.setApplyCash(applyCash);
		
		String trade_no = ChatUtil.create_timestamp(); //商户订单号
		try {
			//获取当前看用户信息
			WatchUser user = watchUserService.findOne("userOpenId",userOpenId);
			if(null != user){
				SortedMap<Object, Object> parm = new TreeMap<Object, Object>();
				parm.put("mch_appid", appid); //公众账号appid
	            parm.put("mchid", mchid); //商户号
	            parm.put("nonce_str", RedPacketUtil.pay_nonce_str()); //随机字符串
	            parm.put("partner_trade_no", trade_no); //商户订单号
	            parm.put("openid", userOpenId); //用户openid  
	            parm.put("check_name", "NO_CHECK"); //校验用户姓名选项:NO_CHECK-不校验真实姓名 OPTION_CHECK,FORCE_CHECK-强校验真实姓名
	            //parm.put("re_user_name", "安迪"); //check_name设置为FORCE_CHECK或OPTION_CHECK，则必填
//	            parm.put("amount", "100"); //转账金额,单位为分  单笔最小金额默认为1元
	            parm.put("amount",  RedPacketUtil.get_total_fee(applyCash)); //转账金额,单位为分  单笔最小金额默认为1元
	            parm.put("desc", "提现"); //企业付款描述信息
	            parm.put("spbill_create_ip", RedPacketUtil.getHostAddress()); //服务器Ip地址
	            String sign = RedPacketUtil.createSign("UTF-8", parm, apikey);
	            parm.put("sign", sign);
				
	            String requestXML = RedPacketUtil.getRequestXml(parm);
//		  	    String xmlStr = WxHttpUtil.postData(TRANSFERS_PAY, requestXML);
	            Live live = liveService.find(liveId);
	            if(null != live){
	    			// 获取线路信息
	            	Line line = lineService.find(live.getMainid());
	    			// 获取机构信息中的appid，appsecret
	    			Organ organ = organService.find(line.getOrganid());
	            	if(null != organ){
	            		    String path = request.getSession().getServletContext().getRealPath("/");
	            		    String currentPath = new File(path).getParent()+organ.getDiploma();
	            		 	String xmlStr =  HttpUtils.posts(mchid,currentPath,TRANSFERS_PAY,requestXML);
		       		  	    if(xmlStr.indexOf("SUCCESS") != -1) {   
		       		        	  Map<String, String> map = XMLUtil.doXMLParse(xmlStr); 
		       		        	  String result_code = map.get("result_code");
		       		        	  if(StringUtil.isNotEmpty(result_code) && result_code.equals("SUCCESS")){
		       		        		  statusCode = "1"; 
		       		        	  	  String partner_trade_no = map.get("partner_trade_no");  //商户订单号 
		       		        		  String payment_no = map.get("payment_no");      //企业付款成功，返回的微信订单号
		       		        		  String payment_time = map.get("payment_time");  //企业付款成功时间
		       		        		
		       		        		  //当前余额
		       		        		  double currentMoney =  RedPacketUtil.sub(user.getTotal(), applyCash);
		       		        		  
		       		        		  cash.setOrderNo(partner_trade_no);
		       		        		  cash.setStatus("2");
		       		        		  cash.setTotal(currentMoney);
		       		        		  cash.setCreateTime(payment_time);
		       		        		  applyCashService.save(cash);
		       		        		
		       		  				  user.setTotal(currentMoney);
		       		  				  user.setUpdateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
		       		  				  watchUserService.update(user);
		       		        		  
		       		        	  }else{
		       		        		  String err_code_des = map.get("err_code_des");
		       		        		  result = err_code_des;  
		       		        	  }
		       		          }else{
		       		        	  result = "系统繁忙,请稍后再试!";
		       		          }
	            	}else{
	            		result = "获取商户证书信息失败,请稍后重试！";
	            	}
	            }else{
	            	result = "获取商户证书信息失败,请稍后重试！";
	            }
	            
		  	    
		  	    
		  	  if(statusCode.equals("2")){  //失败时
					cash.setOrderNo(trade_no);
					cash.setStatus("3");   //1-申请提现 ，2-成功， 3-失败
					cash.setTotal(user.getTotal());
					cash.setCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
					applyCashService.save(cash);
				}
				
			}else{
				result = "获取用户信息失败,请稍后重试！";
			}
			
			
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "修改异常", e);
			result = "连接失败，请稍后重试！";
		}
		
		jsonMap.put("result", result);
		return jsonMap;
	} 
	
	
	/**
	 * 处理用户提现请求(接口)
	 * @param watchUser
	 * @return
	 */
	@RequestMapping("/isSecretKeyCet")
	@ResponseBody
	public Map<String, Object> isSecretKeyCet(long liveid,String passwrod){
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			List<SecretKeyl> sk=secretKeylService.find("liveId",liveid);
			Map<String, Object> watchUser = (Map<String, Object>) session
					.getAttribute("watchUser");
			if(sk.size()==1){//先判断是单一秘钥吧
				SecretKeyl ske=sk.get(0); 
				if(StringUtil.isNullOrEmpty(ske.getUserOpenId())){//再判断微信id未绑定
					if(ske.getPasswork().equals(passwrod)){
						jsonMap.put("result", "成功");
						SecretKeyCet skc=new SecretKeyCet();
						skc.setCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
						skc.setUserOpenId(watchUser.get("openid")+"");
						skc.setUserNickName(watchUser.get("nickname")+"");
						skc.setPasswork(passwrod);
						skc.setIsStatus("1");
						skc.setLiveId(liveid);
						secretKeyCetService.save(skc);
					}
				}
			}else{//判断是多秘钥吧
				List<SecretKeyl> skl=secretKeylService.find("liveId",liveid,"passwork",passwrod,"userOpenId",watchUser.get("openid")+"");
						if(skl.size()>0){
							jsonMap.put("result", "成功");
							SecretKeyCet skc=new SecretKeyCet();
							skc.setCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
							skc.setUserOpenId(watchUser.get("openid")+"");
							skc.setUserNickName(watchUser.get("nickname")+"");
							skc.setPasswork(passwrod);
							skc.setIsStatus("1");
							skc.setLiveId(liveid);
							secretKeyCetService.save(skc);
						}else{//第几一次进来绑定
							List<SecretKeyl> skls=secretKeylService.find("liveId",liveid,"passwork",passwrod);
							if(skls.size()>0){
								SecretKeyl skll=skls.get(0);
								skll.setUserOpenId(watchUser.get("openid")+"");
								skll.setUserNickName(watchUser.get("nickname")+"");
								skll.setUserSex(watchUser.get("sex").toString());
								skll.setCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
								secretKeylService.update(skll);
								SecretKeyCet skc=new SecretKeyCet();
								skc.setCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
								skc.setUserOpenId(watchUser.get("openid")+"");
								skc.setUserNickName(watchUser.get("nickname")+"");
								skc.setPasswork(passwrod);
								skc.setIsStatus("1");
								skc.setLiveId(liveid);
								secretKeyCetService.save(skc);
								jsonMap.put("result", "成功");
							}
						}
			}
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "异常");
		}
		return  jsonMap;
	}
	  
}
